#!/bin/bash

# OpenVPN 监控系统 Docker 构建脚本

set -e

echo "=========================================="
echo "OpenVPN 监控系统 Docker 构建脚本"
echo "=========================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查Docker是否安装
check_docker() {
    echo -e "${YELLOW}检查Docker环境...${NC}"
    if ! command -v docker &> /dev/null; then
        echo -e "${RED}错误: Docker未安装${NC}"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        echo -e "${RED}错误: Docker Compose未安装${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✓ Docker环境检查通过${NC}"
}

# 创建必要目录
create_directories() {
    echo -e "${YELLOW}创建必要目录...${NC}"
    mkdir -p data
    mkdir -p config
    mkdir -p backup
    echo -e "${GREEN}✓ 目录创建完成${NC}"
}

# 停止现有容器
stop_containers() {
    echo -e "${YELLOW}停止现有容器...${NC}"
    docker-compose down 2>/dev/null || true
    echo -e "${GREEN}✓ 容器已停止${NC}"
}

# 清理旧镜像
cleanup_images() {
    echo -e "${YELLOW}清理旧镜像...${NC}"
    docker image prune -f
    echo -e "${GREEN}✓ 镜像清理完成${NC}"
}

# 构建镜像
build_image() {
    echo -e "${YELLOW}构建Docker镜像...${NC}"
    docker-compose build --no-cache
    echo -e "${GREEN}✓ 镜像构建完成${NC}"
}

# 启动服务
start_services() {
    echo -e "${YELLOW}启动服务...${NC}"
    docker-compose up -d
    echo -e "${GREEN}✓ 服务启动完成${NC}"
}

# 等待服务就绪
wait_for_service() {
    echo -e "${YELLOW}等待服务就绪...${NC}"
    local max_attempts=30
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        if curl -f http://localhost:5000/api/online-users >/dev/null 2>&1; then
            echo -e "${GREEN}✓ 服务已就绪${NC}"
            return 0
        fi
        
        echo -n "."
        sleep 2
        attempt=$((attempt + 1))
    done
    
    echo -e "${RED}✗ 服务启动超时${NC}"
    return 1
}

# 显示状态信息
show_status() {
    echo -e "${YELLOW}服务状态:${NC}"
    docker-compose ps
    
    echo -e "\n${YELLOW}访问地址:${NC}"
    echo -e "${GREEN}http://localhost:5000${NC}"
    
    echo -e "\n${YELLOW}查看日志:${NC}"
    echo -e "${GREEN}docker-compose logs -f openvpn-monitor${NC}"
    
    echo -e "\n${YELLOW}停止服务:${NC}"
    echo -e "${GREEN}docker-compose down${NC}"
}

# 主函数
main() {
    case "${1:-build}" in
        "build")
            check_docker
            create_directories
            stop_containers
            cleanup_images
            build_image
            start_services
            wait_for_service
            show_status
            ;;
        "start")
            check_docker
            start_services
            wait_for_service
            show_status
            ;;
        "stop")
            stop_containers
            echo -e "${GREEN}✓ 服务已停止${NC}"
            ;;
        "restart")
            check_docker
            stop_containers
            start_services
            wait_for_service
            show_status
            ;;
        "logs")
            docker-compose logs -f openvpn-monitor
            ;;
        "clean")
            echo -e "${YELLOW}清理所有容器和镜像...${NC}"
            docker-compose down -v
            docker image prune -f
            docker system prune -f
            echo -e "${GREEN}✓ 清理完成${NC}"
            ;;
        "backup")
            echo -e "${YELLOW}备份数据库...${NC}"
            if [ -f "data/openvpn_monitor.db" ]; then
                cp data/openvpn_monitor.db "backup/openvpn_monitor_$(date +%Y%m%d_%H%M%S).db"
                echo -e "${GREEN}✓ 备份完成${NC}"
            else
                echo -e "${YELLOW}数据库文件不存在，跳过备份${NC}"
            fi
            ;;
        *)
            echo "用法: $0 {build|start|stop|restart|logs|clean|backup}"
            echo ""
            echo "命令说明:"
            echo "  build   - 构建镜像并启动服务（默认）"
            echo "  start   - 启动服务"
            echo "  stop    - 停止服务"
            echo "  restart - 重启服务"
            echo "  logs    - 查看日志"
            echo "  clean   - 清理所有容器和镜像"
            echo "  backup  - 备份数据库"
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@" 